package com.dajie.pt.service;

import com.dajie.pt.service.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.Format;
import java.text.MessageFormat;
import java.util.*;
import java.sql.*;

/**
 * Created by yunbinan on 15-6-11.
 */
public class Dashan {
    private static Logger logger = LoggerFactory.getLogger(Dashan.class);
    private Connection mailConnection = null;
    private static final int STATUS_2 = 428;
    private static final int STATUS_1_BAILING = 425;
    private static final int STATUS_1_XUESHENG = 429;
    private static final int STATUS_1_OTHER = 430;
    public static final int TYPE = 3000;
    private static SendSms sendSms = new SendSms();

    public Dashan() {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:cobar://cobarvip:12001/DB_MAIL?autoCommit=true&autoReconnect=true&useUnicode=true&tinyInt1isBit=false&zeroDateTimeBehavior=round&characterEncoding=UTF-8&yearIsDateType=false&zeroDateTimeBehavior=convertToNull";
        String user = "platformol";
        String password = "platformol-3";
        Connection conn = null;
        try {
            Class.forName(driver);
            mailConnection = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            logger.error(e.toString());
        } catch (SQLException e) {
            logger.error(e.toString());
        }
    }

    class DashanData {
        public DashanData(int fromUid, int toUid, int status) {
            this.fromUid = fromUid;
            this.toUid = toUid;
            this.status = status;
        }

        private int fromUid = 0;
        private int toUid = 0;
        private int status = 0;
    }

    public List<DashanData> getDashanData(String startTime, String endTime) {
        RedisServer redisServer = RedisServer.getInstance();
        List<DashanData> dashanDatas = new ArrayList();
        while (redisServer.llen("dashansms") > 0) {
            String strObject = redisServer.lpop("dashansms");
            String[] info = strObject.split("-");
            dashanDatas.add(new DashanData(Integer.parseInt(info[0]), Integer.parseInt(info[1]), Integer.parseInt(info[2])));
        }
        return dashanDatas;
    }

    public int insertHasSendToDb(int uid, String mobile) {
        Statement statement = null;
        ResultSet rs = null;
        int result = 0;
        String t_sql = "insert into tb_djgk_dashan (uid,mobile,create_date) values (%s,'%s',now())";
        String sql = String.format(t_sql, uid, mobile);
        try {
            statement = mailConnection.createStatement();
            result = statement.executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public Set<String> getCurrentDayHasSendMobile() {
        Set<String> mobiles = new HashSet<String>();
        Statement statement = null;
        ResultSet rs = null;
        int result = 0;
        String sql = "select distinct mobile from tb_djgk_dashan where update_date >= curdate()";
        try {
            statement = mailConnection.createStatement();
            rs = statement.executeQuery(sql);
            while (rs.next()) {
                mobiles.add(rs.getString(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return mobiles;
    }

    /*  public Set<String> getBeyondFrequencyMobile() {
          Set<String> mobiles = new HashSet<String>();
          Statement statement = null;
          ResultSet rs = null;
          int result = 0;
          String sql = "select mobile from tb_djgk_dashan group by mobile having count(1) >= 7";
          try {
              statement = mailConnection.createStatement();
              rs = statement.executeQuery(sql);
              while (rs.next()) {
                  mobiles.add(rs.getString(1));
              }
          } catch (SQLException e) {
              e.printStackTrace();
          } finally {
              try {
                  statement.close();
              } catch (SQLException e) {
                  e.printStackTrace();
              }
          }
          return mobiles;
      }*/
    public Boolean getBeyondFrequencyMobile(String mobile) {
        if (mobile == null || "".equals(mobile)) {
            return true;
        }
        Statement statement = null;
        ResultSet rs = null;
        int result = 0;
        String sql = String.format("select count(1) from tb_djgk_dashan where mobile='%s';", mobile);
        try {
            statement = mailConnection.createStatement();
            rs = statement.executeQuery(sql);
            while (rs.next()) {
                result = rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                statement.close();
            } catch (SQLException e) {
                logger.error("ERROR:{}", e);
            }
        }
        return result >= 7;
    }

    public static void main(String[] args) {
        logger.error("args size:{}", args.length);
        if (args.length != 2) {
            logger.error("args length error");
            System.exit(0);
        }
        String start_time = args[0];
        String end_time = args[1];
        logger.error("main --> input args start_time:{} end_time:{} ", start_time, end_time);
        Dashan dashan = new Dashan();
        Set<Integer> hasSendMemory = new HashSet<Integer>();  //根据uid避免重复
        Set<String> hasSendDb = dashan.getCurrentDayHasSendMobile();      //根据手机号避免重复 每日去重
        logger.error("main --> hasSendDb size:{}", hasSendDb.size());
        List<DashanData> dashanDatas = dashan.getDashanData(start_time, end_time);
        logger.error("main --> dashanData size:{}", dashanDatas.size());
        Map<String, String> map = new HashMap<String, String>();
        String toUname = "";
        String fromUname = "";
        String fromCorp = "";
        String toMobile = "";
        String fromSchool = "";
        boolean isBeyond = false;
        for (DashanData dashanData : dashanDatas) {
            if (dashanData.fromUid == 164692 || dashanData.fromUid == 10380793) {
                logger.error("main --> spam fromUid:{}", dashanData.fromUid);
                continue;
            }
            if (hasSendMemory.contains(dashanData.toUid)) {
                logger.error("main --> hasSendMemory toUid:{}", dashanData.toUid);
                continue;
            }
            switch (dashanData.status) {
                case 0:
                    int identity = CommonUtil.getIdentityByUid(dashanData.fromUid);
                    switch (identity) {
                        case 1:
                            //{被搭讪者to_uid姓名}，{搭讪者from_uid姓名} （{搭讪者from_uid当前身份公司名}
                            // map = new HashMap<String, String>();
                            toUname = CommonUtil.getUnameByUid(dashanData.toUid);
                            fromUname = CommonUtil.getUnameByUid(dashanData.fromUid);
                            fromCorp = CommonUtil.getCorpNameByUid(dashanData.fromUid);
                            toMobile = CommonUtil.getMobileByUid(dashanData.toUid);
                            isBeyond = dashan.getBeyondFrequencyMobile(toMobile);

                            map.put("toUname", toUname);
                            map.put("fromUname", fromUname);
                            map.put("fromCorp", fromCorp);
                            map.put("MOBILE", toMobile);
                            if (!StringUtil.isEmpty(fromUname) && !StringUtil.isEmpty(toUname) && !StringUtil.isEmpty(toMobile) && !StringUtil.isEmpty(fromCorp)) {
                                map.put("smsUrl", CommonUtil.smsUrl("gallery=" + "guodu" + "&signature=" + "dajie" + "&ch=djgkdashan" + TimeUtil.getST() + STATUS_1_BAILING + "&st=" + TimeUtil.getST() + "&sms_uid=" + dashanData.toUid));
                                if (hasSendDb.contains(toMobile) || isBeyond) {
                                    logger.error("main --> hasSendDb toUid:{} toMobile:{} contains:{}", dashanData.toUid, toMobile, isBeyond);
                                    continue;
                                }
                                //String result = SendSms.sendSms(TYPE, STATUS_1_BAILING, map);
                                String result = sendSms.sendSmsNew(toMobile, String.valueOf(STATUS_1_BAILING), map);
                                if (result.contains("1")) {
                                    hasSendDb.add(toMobile);
                                    hasSendMemory.add(dashanData.toUid);
                                    dashan.insertHasSendToDb(dashanData.toUid, toMobile);
                                    logger.error("main --> sendSms success toUid:{} fromUid:{} toMobile:{} tplId:{} result:{} map:{}", dashanData.toUid, dashanData.fromUid, toMobile, STATUS_1_BAILING, result, map.toString());
                                } else {
                                    logger.error("main --> sendSms fail toUid:{} toMobile:{} identity:{} result:{} map:{}", dashanData.toUid, toMobile, identity, result, map.toString());
                                }
                            } else {
                                logger.error("main --> getInfo lost fromUid:{} toUid:{} identity:{} map:{}", dashanData.fromUid, dashanData.toUid, identity, map.toString());
                            }
                            break;
                        case 3:
                            //{被搭讪者to_uid姓名}，{搭讪者from_uid姓名} （{搭讪者from_uid当前身份学校名}
                            map = new HashMap<String, String>();
                            toUname = CommonUtil.getUnameByUid(dashanData.toUid);
                            fromUname = CommonUtil.getUnameByUid(dashanData.fromUid);
                            fromSchool = CommonUtil.getSchoolNameByUid(dashanData.fromUid);
                            toMobile = CommonUtil.getMobileByUid(dashanData.toUid);
                            isBeyond = dashan.getBeyondFrequencyMobile(toMobile);

                            map.put("toUname", toUname);
                            map.put("fromUname", fromUname);
                            map.put("fromSchool", fromSchool);
                            map.put("MOBILE", toMobile);
                            if (!StringUtil.isEmpty(fromUname) && !StringUtil.isEmpty(toUname) && !StringUtil.isEmpty(toMobile) && !StringUtil.isEmpty(fromSchool)) {
                                map.put("smsUrl", CommonUtil.smsUrl("gallery=" + "guodu" + "&signature=" + "dajie" + "&ch=djgkdashan" + TimeUtil.getST() + STATUS_1_XUESHENG + "&st=" + TimeUtil.getST() + "&sms_uid=" + dashanData.toUid));
                                if (hasSendDb.contains(toMobile) || isBeyond) {
                                    logger.error("main --> hasSendDb toUid:{} toMobile:{} contains:{}", dashanData.toUid, toMobile, isBeyond);
                                    continue;
                                }
                                //String result = SendSms.sendSms(TYPE, STATUS_1_XUESHENG, map);
                                String result = sendSms.sendSmsNew(toMobile, String.valueOf(STATUS_1_XUESHENG), map);
                                if (result.contains("1")) {
                                    hasSendDb.add(toMobile);
                                    hasSendMemory.add(dashanData.toUid);
                                    dashan.insertHasSendToDb(dashanData.toUid, toMobile);
                                    logger.error("main --> sendSms success toUid:{} fromUid:{} toMobile:{} tplId:{} result:{} map:{}", dashanData.toUid, dashanData.fromUid, toMobile, STATUS_1_XUESHENG, result, map.toString());
                                } else {
                                    logger.error("main --> sendSms fail toUid:{} toMobile:{} identity:{} result:{} map:{}", dashanData.toUid, toMobile, identity, result, map.toString());
                                }
                            } else {
                                logger.error("main --> getInfo lost fromUid:{} toUid:{} identity:{} map:{}", dashanData.fromUid, dashanData.toUid, identity, map.toString());
                            }
                            break;
                        case 4:
                            //{被搭讪者to_uid姓名}，{搭讪者from_uid姓名} （{搭讪者from_uid当前身份学校名}
                            map = new HashMap<String, String>();
                            toUname = CommonUtil.getUnameByUid(dashanData.toUid);
                            fromUname = CommonUtil.getUnameByUid(dashanData.fromUid);
                            fromSchool = CommonUtil.getSchoolNameByUid(dashanData.fromUid);
                            toMobile = CommonUtil.getMobileByUid(dashanData.toUid);
                            isBeyond = dashan.getBeyondFrequencyMobile(toMobile);

                            map.put("toUname", toUname);
                            map.put("fromUname", fromUname);
                            map.put("fromSchool", fromSchool);
                            map.put("MOBILE", toMobile);
                            if (!StringUtil.isEmpty(fromUname) && !StringUtil.isEmpty(toUname) && !StringUtil.isEmpty(toMobile) && !StringUtil.isEmpty(fromSchool)) {
                                map.put("smsUrl", CommonUtil.smsUrl("gallery=" + "guodu" + "&signature=" + "dajie" + "&ch=djgkdashan" + TimeUtil.getST() + STATUS_1_XUESHENG + "&st=" + TimeUtil.getST() + "&sms_uid=" + dashanData.toUid));
                                if (hasSendDb.contains(toMobile) || isBeyond) {
                                    logger.error("main --> hasSendDb toUid:{} toMobile:{} contains:{}", dashanData.toUid, toMobile, isBeyond);
                                    continue;
                                }
                                //String result = SendSms.sendSms(TYPE, STATUS_1_XUESHENG, map);
                                String result = sendSms.sendSmsNew(toMobile, String.valueOf(STATUS_1_XUESHENG), map);
                                if (result.contains("1")) {
                                    hasSendDb.add(toMobile);
                                    hasSendMemory.add(dashanData.toUid);
                                    dashan.insertHasSendToDb(dashanData.toUid, toMobile);
                                    logger.error("main --> sendSms success toUid:{} fromUid:{} toMobile:{} tplId:{} result:{} map:{}", dashanData.toUid, dashanData.fromUid, toMobile, STATUS_1_XUESHENG, result, map.toString());
                                } else {
                                    logger.error("main --> sendSms fail toUid:{} toMobile:{} identity:{} result:{} map:{}", dashanData.toUid, toMobile, identity, result, map.toString());
                                }
                            } else {
                                logger.error("main --> getInfo lost fromUid:{} toUid:{} identity:{} map:{}", dashanData.fromUid, dashanData.toUid, identity, map.toString());
                            }
                            break;
                        default:
                            //{被搭讪者to_uid姓名}，{搭讪者from_uid姓名}
                            map = new HashMap<String, String>();
                            toUname = CommonUtil.getUnameByUid(dashanData.toUid);
                            fromUname = CommonUtil.getUnameByUid(dashanData.fromUid);
                            toMobile = CommonUtil.getMobileByUid(dashanData.toUid);
                            isBeyond = dashan.getBeyondFrequencyMobile(toMobile);

                            map.put("toUname", toUname);
                            map.put("fromUname", fromUname);
                            map.put("MOBILE", toMobile);
                            if (!StringUtil.isEmpty(fromUname) && !StringUtil.isEmpty(toUname) && !StringUtil.isEmpty(toMobile)) {
                                map.put("smsUrl", CommonUtil.smsUrl("gallery=" + "guodu" + "&signature=" + "dajie" + "&ch=djgkdashan" + TimeUtil.getST() + STATUS_1_OTHER + "&st=" + TimeUtil.getST() + "&sms_uid=" + dashanData.toUid));
                                if (hasSendDb.contains(toMobile) || isBeyond) {
                                    logger.error("main --> hasSendDb toUid:{} toMobile:{} contains:{}", dashanData.toUid, toMobile, isBeyond);
                                    continue;
                                }
                                //String result = SendSms.sendSms(TYPE, STATUS_1_OTHER, map);
                                String result = sendSms.sendSmsNew(toMobile, String.valueOf(STATUS_1_OTHER), map);
                                if (result.contains("1")) {
                                    hasSendDb.add(toMobile);
                                    hasSendMemory.add(dashanData.toUid);
                                    dashan.insertHasSendToDb(dashanData.toUid, toMobile);
                                    logger.error("main --> sendSms success toUid:{} fromUid:{} toMobile:{} tplId:{} result:{} map:{}", dashanData.toUid, dashanData.fromUid, toMobile, STATUS_1_OTHER, result, map.toString());
                                } else {
                                    logger.error("main --> sendSms fail toUid:{} toMobile:{} identity:{} result:{} map:{}", dashanData.toUid, toMobile, identity, result, map.toString());
                                }
                            } else {
                                logger.error("main --> getInfo lost fromUid:{} toUid:{} identity:{} map:{}", dashanData.fromUid, dashanData.toUid, identity, map.toString());
                            }
                            break;
                    }
                    break;
                case 1:
                    //{被搭讪者to_uid姓名}，你曾感兴趣的{搭讪者from_uid姓名}
                    map = new HashMap<String, String>();
                    toUname = CommonUtil.getUnameByUid(dashanData.toUid);
                    fromUname = CommonUtil.getUnameByUid(dashanData.fromUid);
                    toMobile = CommonUtil.getMobileByUid(dashanData.toUid);
                    isBeyond = dashan.getBeyondFrequencyMobile(toMobile);

                    map.put("toUname", toUname);
                    map.put("fromUname", fromUname);
                    map.put("MOBILE", toMobile);
                    if (!StringUtil.isEmpty(fromUname) && !StringUtil.isEmpty(toUname) && !StringUtil.isEmpty(toMobile)) {
                        map.put("smsUrl", CommonUtil.smsUrl("gallery=" + "guodu" + "&signature=" + "dajie" + "&ch=djgkdashan" + TimeUtil.getST() + STATUS_2 + "&st=" + TimeUtil.getST() + "&sms_uid=" + dashanData.toUid));
                        if (hasSendDb.contains(toMobile) || isBeyond) {
                            logger.error("main --> hasSendDb toUid:{} toMobile:{} contains:{}", dashanData.toUid, toMobile, isBeyond);
                            continue;
                        }
                        //String result = SendSms.sendSms(TYPE, STATUS_2, map);
                        String result = sendSms.sendSmsNew(toMobile, Integer.toString(STATUS_2), map);
                        if (result.contains("1")) {
                            hasSendDb.add(toMobile);
                            hasSendMemory.add(dashanData.toUid);
                            dashan.insertHasSendToDb(dashanData.toUid, toMobile);
                            logger.error("main --> sendSms success toUid:{} fromUid:{} toMobile:{} tplId:{} result:{} map:{}", dashanData.toUid, dashanData.fromUid, toMobile, STATUS_2, result, map.toString());
                        } else {
                            logger.error("main --> sendSms fail toUid:{} toMobile:{} result:{} map:{}", dashanData.toUid, toMobile, result, map.toString());
                        }
                    } else {
                        logger.error("main --> getInfo lost fromUid:{} toUid:{} map:{}", dashanData.fromUid, dashanData.toUid, map.toString());
                    }
                    break;
            }
        }
        if (sendSms.getLeftSms().size() > 0 && sendSms.getLeftSms().size() < 100) {
            sendSms.sendSmsBatch(sendSms.getLeftSms());
        }

    }

}
